package com.apache.common.plugins.flow;

import com.apache.api.manager.ProxyManager;
import com.apache.api.vo.ParamsVo;
import com.apache.api.vo.ResultEntity;
import com.apache.cache.util.Validator;
import com.apache.client.UctProtoclClient;
import com.apache.exception.BusinessException;
import com.apache.ius.plugin.CustomMethodPlugin;
import com.apache.ius.plugin.IusPluginUtil;
import com.apache.rpc.common.LoadRpcService;
import com.apache.rpc.entity.InterfaceRegister;
import com.apache.tools.DataMap;
import com.apache.tools.DateUtils;
import com.apache.tools.StrUtil;
import com.apache.uct.common.entity.User;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 审核插件：完成当前审核表audit的审核操作，并且根据审核规则去初始化审核数据
 */
@SuppressWarnings("serial")
public class FlowNextPluginImpl implements CustomMethodPlugin {

    protected Logger log = Logger.getLogger(getClass());

    public Object doInvoke(Map<String, Object> param) {
        beforeInvoke(param);
        return null;
    }

    public Object beforeInvoke(Map<String, Object> param) {
        String auditsId = String.valueOf(param.get("auditsId"));
        String auditFlag = Validator.getDefaultStr(String.valueOf(param.get("auditFlag")), "T");
        String auditOpinion = String.valueOf(param.get("auditOpinion"));
        String pid = String.valueOf(param.get("pid"));//非必填项，如果传参则用传过来的参数值，如不传则用上一条数据的pid的值。
        String colNameY = String.valueOf(param.get("colNameY"));//非必填项，如果传参则用传过来的参数值，如不传则用上一条数据的colNameY的值。
        String colNameN = String.valueOf(param.get("colNameN"));//伤者名称，
        String proName = String.valueOf(param.get("proName"));//车牌号，
        String linkUrl = String.valueOf(param.get("linkUrl"));//伤者电话
        String personId = String.valueOf(param.get("personId"));//伤者电话
        String orgId = String.valueOf(param.get("orgId"));//伤者电话
        String lastId = String.valueOf(param.get("lastId"));//上一环节业务主键
        String createUser = String.valueOf(param.get("createUser"));//上一环节业务主键
        String isRevision = String.valueOf(param.get("isRevision"));//isRevision是否改派
        String taskSource = String.valueOf(param.get("taskSource"));//isRevision是否改派
        String deptId = String.valueOf(param.get("deptId"));//唯一索引标识
        String delStatus = String.valueOf(param.get("delStatus"));//唯一索引标识
        String district = String.valueOf(param.get("district"));//任务区县代码
        String auditsStatus = "91";
        if("F".equals(auditFlag)){
            auditsStatus="90";
        }
        String objColName = "";
        if (Validator.isNull(auditsId)) {
            throw new BusinessException(
                    "auditsId参数不能为空！请注意不是auditId而是auditsId！");
        }
//        log.info("【开始执行审核任务】 - > auditsId="+auditsId+",auditFlag="+auditFlag+",auditOpinion="+auditOpinion);
        //更新audit表
        ResultEntity upResult = updateAudit(auditsId, auditsStatus, auditOpinion, param);
        if (!upResult.getResult().equals("T")) {
            throw new BusinessException("执行失败！");
        }

        String searchObjName = "s_sysAudit";
        Map<String, Object> whereMap = new HashMap<String, Object>();
        whereMap.put("sysAudit.w_auditsId", auditsId);
        ResultEntity auditResult = (ResultEntity) IusPluginUtil.getInstance().select(String.valueOf(param.get("datasource")),"obj",searchObjName,whereMap);
        DataMap auditInfoDataMap = (DataMap) auditResult.getEntity();
        param.put("proId",String.valueOf(auditInfoDataMap.get("proId")));
        param.put("pid",Validator.getDefaultStr(pid,String.valueOf(auditInfoDataMap.get("pid"))));//主表主键
        param.put("colNameY",Validator.getDefaultStr(colNameY,String.valueOf(auditInfoDataMap.get("colNameY"))));//colNameY
        param.put("colNameN",Validator.getDefaultStr(colNameN,String.valueOf(auditInfoDataMap.get("colNameN"))));//colNameN
        param.put("proName",Validator.getDefaultStr(proName,String.valueOf(auditInfoDataMap.get("proName"))));//proName
        param.put("linkUrl",Validator.getDefaultStr(linkUrl,String.valueOf(auditInfoDataMap.get("linkUrl"))));//linkUrl
        param.put("personId",Validator.getDefaultStr(personId,String.valueOf(auditInfoDataMap.get("personId"))));//personId
        param.put("lastId",Validator.getDefaultStr(lastId,String.valueOf(auditInfoDataMap.get("lastId"))));//lastId
        param.put("orgId",Validator.getDefaultStr(orgId,String.valueOf(auditInfoDataMap.get("orgId"))));//checkUser
        param.put("isRevision",Validator.getDefaultStr(isRevision,String.valueOf(auditInfoDataMap.get("isRevision"))));//isRevision是否改派
        param.put("taskSource",Validator.getDefaultStr(taskSource,String.valueOf(auditInfoDataMap.get("taskSource"))));//taskSource任务来源
        if(Validator.isEmpty(deptId)){
            param.put("deptId",deptId);
        }
        if(Validator.isEmpty(delStatus)) {
            param.put("delStatus",delStatus);
        }
        if(Validator.isEmpty(district)) {
            param.put("district",district);
        }

        //当执行pageName和formName时，根据判断条件执行对应的字段修改
//        String updateColNameParam=String.valueOf(auditInfoDataMap.get("colNameY"));
//
//        if("F".equals(auditFlag)){
//            updateColNameParam =String.valueOf(auditInfoDataMap.get("colNameN"));
//        }
//        if(Validator.isNotNull(updateColNameParam)){
//            String str[] =updateColNameParam.split(",");
//            for (String colParam: str) {
//                if(Validator.isNotNull(colParam)){
//                    String key = colParam.split("=")[0];
//                    String value = colParam.split("=")[1];
//                    param.put(key,value);
//                }
//            }
//        }

        //根据当前nodeCode去找下一节点的值并且insert到audit中
        Map<String, Object> whereMap_auditRule = new HashMap<String, Object>();
        whereMap_auditRule.put("sysAuditRule.w_taskNo",String.valueOf(auditInfoDataMap.get("taskNo")));
        ResultEntity dymicSqlParamResult = (ResultEntity) IusPluginUtil.getInstance().select(String.valueOf(param.get("datasource")),"list","s_sysAuditRule",whereMap_auditRule);
        List<DataMap> firstNodeList = (List<DataMap>) dymicSqlParamResult.getEntity();
        String nextNodeCode="";
        for (DataMap node:firstNodeList) {
            String nodeType="";
            nodeType = String.valueOf(node.get("nodeType"));
            String nodeConfig = String.valueOf(node.get("nodeConfig"));
            JSONObject jObject = JSONObject.fromObject(nodeConfig);
            JSONArray jsonArray = (JSONArray)jObject.get("nexts");
            if(jsonArray.size()>0){
                for(int i=0;i<jsonArray.size();i++){
                    JSONObject job = jsonArray.getJSONObject(i);  // 遍历 jsonarray 数组，把每一个对象转成 json 对象
                    nextNodeCode = String.valueOf(job.get("code"));
                    DataMap nextTaskNodeInfo = getNodeByCode(param,nextNodeCode);
                    if(nextTaskNodeInfo!=null){
//                        System.out.println("======================="+nextTaskNodeInfo.get("taskName"));
                        //            //如果是end节点，则不插入
                        if(!"end".equals(nextTaskNodeInfo.get("nodeType"))){
                            nextTaskNodeInfo.put("datasource",String.valueOf(param.get("datasource")));
                            nextTaskNodeInfo.put("pro_id",String.valueOf(param.get("proId")));
                            nextTaskNodeInfo.put("pid",String.valueOf(param.get("pid")));
                            nextTaskNodeInfo.put("col_name_y",String.valueOf(param.get("colNameY")));
                            nextTaskNodeInfo.put("col_name_n",String.valueOf(param.get("colNameN")));
                            nextTaskNodeInfo.put("pro_name",String.valueOf(param.get("proName")));
                            nextTaskNodeInfo.put("link_url",String.valueOf(param.get("linkUrl")));
                            nextTaskNodeInfo.put("person_id",String.valueOf(param.get("personId")));
                            nextTaskNodeInfo.put("last_id",String.valueOf(param.get("lastId")));
                            nextTaskNodeInfo.put("org_id",String.valueOf(param.get("orgId")));
                            nextTaskNodeInfo.put("is_revision",String.valueOf(param.get("isRevision")));
                            nextTaskNodeInfo.put("task_source",String.valueOf(param.get("taskSource")));
                            nextTaskNodeInfo.put("dept_id",String.valueOf(param.get("deptId")));
                            nextTaskNodeInfo.put("del_status",String.valueOf(param.get("delStatus")));
                            nextTaskNodeInfo.put("district",String.valueOf(param.get("district")));
                            if(Validator.isNotNull(createUser)){
                                nextTaskNodeInfo.put("check_user",createUser);
                            }else{
                                String checkType = String.valueOf(nextTaskNodeInfo.get("checkType"));
                                if("rule".equals(checkType)){
                                    String checkUser = String.valueOf(nextTaskNodeInfo.get("checkUser"));
                                    Map<String, Object> paramsMap = new HashMap<String, Object>();
                                    paramsMap.put("roleId",checkUser);
                                    paramsMap.put("doCode","userList");
                                    paramsMap.put("Client-IP",param.get("requestIp"));
                                    paramsMap.put("sysPass",param.get("sysPass"));
                                    InterfaceRegister ss =  UctProtoclClient.getInstance().getInterfaceRegister("uct", "uctServer_ip", "uctServer_port");
                                    ResultEntity entity =  LoadRpcService.service().doServiceClient("uctService", "userList", paramsMap,ss);
                                    String checkUsers = "";
                                    if(null != entity.getEntity()){
                                        List<User> userList =(List<User>)entity.getEntity();
                                        for (User user: userList) {
                                            checkUsers = checkUsers==""?user.getUserEname():checkUsers+","+user.getUserEname();
                                        }
                                        nextTaskNodeInfo.put("check_user",checkUsers);
                                    }
                                }
                            }
                            initAudit(nextTaskNodeInfo);
                        }else{
                            log.info("【已到结束节点】流程结束！！");
                        }
                    }

                }
            }

        }

//        return param;

        Map<String, Object> result = new HashMap<String, Object>();
        result.put(CustomMethodPlugin.resultMark, "操作成功");
        result.put(CustomMethodPlugin.pluginInnerReturn, null);
        return result;

    }

    public Object afterInvoke(Map<String, Object> param) {

        // TODO Auto-generated method stub
        return null;
    }

    /**
     * 规则校验入口（专门给系统公式规则提供的）
     *
     * @param paramsVo
     */
    public void run(ParamsVo paramsVo) {
        beforeInvoke(paramsVo.getParams());
    }

    /**
     * description:
     *
     * @param iusProxyManager
     * @param auditsId
     * @return DataMap
     */
    private DataMap getAuditByAuditsId(ProxyManager iusProxyManager, String auditsId) {
        ParamsVo auditVo = new ParamsVo();
        auditVo.setParams("doCode", "dymicSql");
        auditVo.setParams("sqlKeyId", "ByDymicSql");
        auditVo.setParams("resultType", "objInfo");
        auditVo.setParams("resultObjType", "obj");
        auditVo.setKey("iusTransaction");
        auditVo.setParams("modelTypes", "s_sysAudit");
        auditVo.setParams("sysAudit.w_auditsId", auditsId);
        ResultEntity auditResult = (ResultEntity) iusProxyManager.doInvoke(auditVo);
        return (DataMap) auditResult.getEntity();
    }


    /**
     * description:
     *
     * @param nextUser sysAuditRule的taskNo
     * @return DataMap
     */
    private DataMap getAuditRuleByTaskNo(ProxyManager iusProxyManager, String nextUser) {
        ParamsVo params = new ParamsVo();
        params.setParams("doCode", "dymicSql");
        params.setParams("sqlKeyId", "ByDymicSql");
        params.setParams("resultType", "objInfo");
        params.setParams("resultObjType", "obj");
        params.setKey("iusTransaction");
        //通过下一审核节点查询规则
        params.setParams("modelTypes", "s_sysAuditRule");
        params.setParams("sysAuditRule.w_taskNo", nextUser);
        ResultEntity dymicSqlParamResult = (ResultEntity) iusProxyManager.doInvoke(params);
        return (DataMap) dymicSqlParamResult.getEntity();

    }



    private ResultEntity updateAudit(String auditsId,
                                     String auditsStatus, String auditOpinion, Map<String, Object> param) {
        //换成跨数据源的写法
        String saveObjName = "u_sysAudit";
        Map<String, Object> upParamVo = new HashMap<String, Object>();
        upParamVo.put("sysAudit.w_auditsId", auditsId);
        upParamVo.put("sysAudit.auditsStatus", auditsStatus);
        upParamVo.put("sysAudit.auditOpinion", auditOpinion);
        upParamVo.put("sysAudit.modifyTime", DateUtils.Now.fmt_yyyyMMdd_HHmmss());
        upParamVo.put("sysAudit.modifyUser", param.get("sysAudit.modifyUser"));
        ResultEntity result = IusPluginUtil.getInstance().saveInvoke(String.valueOf(param.get("datasource")),saveObjName,upParamVo);
        return result;
    }


    private DataMap getNodeByCode(Map<String, Object> param,String nodeCode) {
        if(StrUtil.isNull(nodeCode)){
            return  null;
        }
        Map<String, Object> whereMap_next = new HashMap<String, Object>();
        whereMap_next.put("sysAuditRule.w_taskNo", nodeCode);
        ResultEntity nextCodeResult = (ResultEntity) IusPluginUtil.getInstance().select(String.valueOf(param.get("datasource")), "obj", "s_sysAuditRule", whereMap_next);
        DataMap nextNodeInfo = (DataMap) nextCodeResult.getEntity();
        String next_nodeType = String.valueOf(nextNodeInfo.get("nodeType"));
        if ("judge".equals(next_nodeType)) {
            //递归
            String nextNode = "";
            String nodeConfig = String.valueOf(nextNodeInfo.get("nodeConfig"));
            JSONObject jObject = JSONObject.fromObject(nodeConfig);
            JSONArray jsonArray = (JSONArray) jObject.get("nexts");
            if (jsonArray.size() > 0) {
                for (int i = 0; i < jsonArray.size(); i++) {
                    JSONObject job = jsonArray.getJSONObject(i);  // 遍历 jsonarray 数组，把每一个对象转成 json 对象
                    nodeCode = String.valueOf(job.get("code"));
                    String rule = String.valueOf(job.get("rule"));
                    if(Validator.isNotNull(rule)){
                        String arg1 = rule.split("==")[0];
                        String arg2 = rule.split("==")[1];
                        if (arg2.equals(param.get(arg1))) {
                            nextNode = String.valueOf(job.get("code"));
                            break;
                        }else{
                            log.error("流程节点判断["+rule+"]不成立，请检查所需参数是否齐全");
                        }
                    }

                }
            }
            return getNodeByCode(param, nextNode);
        }
        return nextNodeInfo;
    }




    private void initAudit(DataMap taskMap){
        String saveObjName = "i_sysAudit";
        Map<String, Object> paramsMap = new HashMap<String, Object>();
        paramsMap.put("sysAudit.auditType",taskMap.get("auditType"));
        paramsMap.put("sysAudit.proId",taskMap.get("proId"));
        paramsMap.put("sysAudit.pid",taskMap.get("pid"));
        paramsMap.put("sysAudit.auditsStatus", "10");
        paramsMap.put("sysAudit.checkUser", taskMap.get("checkUser"));
        paramsMap.put("sysAudit.nextUser", taskMap.get("next"));
        paramsMap.put("sysAudit.lastUser", taskMap.get("last"));
        paramsMap.put("sysAudit.toUrl", taskMap.get("toUrl"));
        paramsMap.put("sysAudit.createTime", DateUtils.Now.fmt_yyyyMMdd_HHmmss());
        paramsMap.put("sysAudit.num", taskMap.get("num"));
        paramsMap.put("sysAudit.colNameY", taskMap.get("colNameY"));
        paramsMap.put("sysAudit.colNameN", taskMap.get("colNameN"));
        paramsMap.put("sysAudit.linkUrl", taskMap.get("linkUrl"));
        paramsMap.put("sysAudit.personId", taskMap.get("personId"));
        paramsMap.put("sysAudit.lastId", taskMap.get("lastId"));
        paramsMap.put("sysAudit.isRevision", taskMap.get("isRevision"));
        paramsMap.put("sysAudit.taskSource", taskMap.get("taskSource"));
        paramsMap.put("sysAudit.ifCustom", taskMap.get("ifCustom"));
        paramsMap.put("sysAudit.sysName", taskMap.get("sysName"));
        paramsMap.put("sysAudit.pageName", taskMap.get("pageName"));
        paramsMap.put("sysAudit.formName", taskMap.get("formName"));
        paramsMap.put("sysAudit.orgId", taskMap.get("orgId"));


        paramsMap.put("sysAudit.proName", taskMap.get("proName"));
        paramsMap.put("sysAudit.taskName", taskMap.get("taskName"));
        paramsMap.put("sysAudit.taskNo", taskMap.get("taskNo"));
        paramsMap.put("sysAudit.colName", taskMap.get("colName"));
        paramsMap.put("sysAudit.tableName", taskMap.get("tableName"));
        paramsMap.put("sysAudit.delStatus", taskMap.get("delStatus"));
        paramsMap.put("sysAudit.district", taskMap.get("district"));
        paramsMap.put("sysAudit.deptId", taskMap.get("deptId"));
        ResultEntity result = IusPluginUtil.getInstance().saveInvoke(String.valueOf(taskMap.get("datasource")),saveObjName,paramsMap);
//            log.info("【初始化第一级审核任务结果】 - > taskName="+taskName+",proName="+name+",result="+ JSONObject.fromObject(result));
        log.info("初始化节点["+taskMap.get("taskNo")+"->"+taskMap.get("taskName")+"]完成");
        if (!result.getResult().equals("T")) {
            throw new BusinessException("执行失败！");
        }

    }


}
